//
//  QKActionSheet.m
//  Cat
//
//  Created by lushitong on 2019/1/1.
//  Copyright © 2019年 lushitong. All rights reserved.
//

#import "QKActionSheet.h"

@interface QKActionSheet ()

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *buttonsView;
@property (nonatomic, strong) UIButton *cancelBtn;

@property (nonatomic, strong) NSMutableArray *buttons;
@property (nonatomic, strong) NSMutableArray *buttonSepViews;

@property (nonatomic, strong) NSLayoutConstraint *buttonsViewBottomInsetConstraint;
@property (nonatomic, strong) NSArray *selfConstraints;

@property (nonatomic, assign) BOOL didSetupConstraints;
@property (nonatomic, assign) BOOL isShowButtons;

@property (nonatomic, copy) void(^clickBlock)(int index);
@property (nonatomic, copy) void(^cancelBlock)(void);

@end

@implementation QKActionSheet

#pragma mark - Pub

+ (instancetype)showInView:(UIView *)view items:(NSArray *)items clickBlock:(void (^)(int))clickBlock cancelBlock:(void (^)(void))cancelBlock {
	
	QKActionSheet *as = [[QKActionSheet alloc] initWithButtons:items];
	as.clickBlock = clickBlock;
	as.cancelBlock = cancelBlock;
	[as showInView:view];
	
	return as;
}

- (void)setCancelColor:(UIColor *)cancelColor {
	[self.cancelBtn setTitleColor:cancelColor forState:UIControlStateNormal];
}

- (instancetype)initWithButtons:(NSArray *)buttons {
	self = [super init];
	if (self) {
		[self loadSubviewsWithButtons:buttons];
	}
	return self;
}

- (void)showInView:(UIView *)view {
	[view addSubview:self];
	
	[self.selfConstraints autoRemoveConstraints];
	self.selfConstraints = [self autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
	
	WEAKSELF;
	
	[UIView animateWithDuration:0.1 animations:^{
		weakSelf.bgView.alpha = 1;
	} completion:^(BOOL finished) {
		
		weakSelf.isShowButtons = YES;
		
		[weakSelf setNeedsUpdateConstraints];
		[weakSelf updateConstraintsIfNeeded];
		
		[UIView animateWithDuration:0.25 animations:^{
			[weakSelf layoutIfNeeded];
		}];
	}];
	
}

- (void)show {
	[self showInView:[UIApplication sharedApplication].keyWindow];
}

#pragma mark - Override

- (void)updateConstraints {
	[super updateConstraints];
	
	static CGFloat btnsViewHeight = 0;
	
	if (!self.didSetupConstraints) {
		NSUInteger buttonCount = self.buttons.count;
		
		if (buttonCount == 0) {
			return;
		}
		
		CGFloat buttonHeight = FloatWith3x(164.0) ;  //按钮的高度
		CGFloat spaceHeight = FloatWith3x(22.0);    //取消按钮跟button之间的空隙
		CGFloat sepLineHeight = 0.5;
		
		//*** buttons添加约束 ***//
		[self.cancelBtn autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
		[self.cancelBtn autoSetDimension:ALDimensionHeight toSize:buttonHeight + TabBarSafeInsetHeight];
		
		UIButton *button = self.buttons[buttonCount - 1];
		
		[button autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.cancelBtn withOffset:-spaceHeight];
		[button autoSetDimension:ALDimensionHeight toSize:buttonHeight];
		[button autoPinEdgeToSuperviewEdge:ALEdgeLeft];
		[button autoPinEdgeToSuperviewEdge:ALEdgeRight];
		
		if (buttonCount > 1) {
			[self.buttons autoAlignViewsToAxis:ALAxisVertical];
			[self.buttons autoMatchViewsDimension:ALDimensionWidth];
			[self.buttons autoMatchViewsDimension:ALDimensionHeight];
			
			UIButton *tempButton = button;
			for (int i = 1; i < buttonCount; i++) {
				button = self.buttons[buttonCount - 1 - i];
				[button autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:tempButton withOffset:-sepLineHeight];
				tempButton = button;
			}
		}
		
		//*** 分割线添加约束 ***//
		NSUInteger sepLineCount = self.buttonSepViews.count;
		if (sepLineCount > 0) {
			UIView *sepLineView = self.buttonSepViews[0];
			
			[sepLineView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(buttonHeight, 0, 0, 0) excludingEdge:ALEdgeBottom];
			[sepLineView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
			[sepLineView autoPinEdgeToSuperviewEdge:ALEdgeRight];
			[sepLineView autoSetDimension:ALDimensionHeight toSize:sepLineHeight];
			
			if (sepLineCount > 1) {
				[self.buttonSepViews autoAlignViewsToAxis:ALAxisVertical];
				[self.buttonSepViews autoMatchViewsDimension:ALDimensionWidth];
				[self.buttonSepViews autoMatchViewsDimension:ALDimensionHeight];
				
				UIView *tempView = sepLineView;
				for (int i = 1; i < sepLineCount; i ++) {
					sepLineView = self.buttonSepViews[i];
					[sepLineView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:tempView withOffset:buttonHeight];
					tempView = sepLineView;
				}
			}
		}
		
		btnsViewHeight = (buttonCount + 1) * buttonHeight + spaceHeight + (buttonCount - 1) * sepLineHeight +  TabBarSafeInsetHeight;
		[self.buttonsView autoSetDimension:ALDimensionHeight toSize:btnsViewHeight];
		[self.buttonsView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
		[self.buttonsView autoPinEdgeToSuperviewEdge:ALEdgeRight];
		
		[self.bgView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
		
		self.didSetupConstraints = YES;
	}
	
	CGFloat bottomInset = self.isShowButtons ? 0 : -btnsViewHeight;
	
	[self.buttonsViewBottomInsetConstraint autoRemove];
	self.buttonsViewBottomInsetConstraint = [self.buttonsView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:bottomInset];
}

#pragma mark - Pri Method

- (void)loadSubviewsWithButtons:(NSArray *)list {
	NSUInteger listCount = list.count;
	
	if (listCount == 0) {
		return;
	}
	
	UIButton *tempButton;
	UIView *tempSepLineView;
	NSString *tempTitle;
	for (int i = 0; i < listCount; i++) {
		tempTitle = list[i];
		
		tempButton = [self createButton];
		tempButton.tag = i;
		[tempButton setTitle:tempTitle forState:UIControlStateNormal];
		if ([tempTitle isEqualToString:@"删除"]) {
			[tempButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
		}
		[tempButton addTarget:self
					   action:@selector(buttonTi:)
			 forControlEvents:UIControlEventTouchUpInside];
		
		[self.buttons addObject:tempButton];
		[self.buttonsView addSubview:tempButton];
		
		if (i < listCount - 1) {
			tempSepLineView = [self createSepLineView];
			[self.buttonSepViews addObject:tempSepLineView];
			[self.buttonsView addSubview:tempSepLineView];
		}
	}
	
	[self.buttonsView addSubview:self.cancelBtn];
	
	[self addSubview:self.bgView];
	[self addSubview:self.buttonsView];
}

- (UIButton *)createButton {
	UIImage *nmImage = [UIImage imageWithColor:COLOR_WITH_HEX(0xfbfbfb)];
	UIImage *hlImage = [nmImage addBlackMask];
	
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.titleLabel.font = [UIFont fontWith3x:52.0];
	[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	[button setBackgroundImage:nmImage forState:UIControlStateNormal];
	[button setBackgroundImage:hlImage forState:UIControlStateHighlighted];
	
	return button;
}

- (UIView *)createSepLineView {
	UIView *view = [UIView new];
	view.backgroundColor = COLOR_WITH_HEX(0xdfdfe2);
	
	return view;
}

- (void)dismiss {
	
	self.isShowButtons = NO;
	
	[self setNeedsUpdateConstraints];
	[self updateConstraintsIfNeeded];
	
	WEAKSELF;
	
	[UIView animateWithDuration:0.3 animations:^{
		weakSelf.bgView.alpha = 0;
		[weakSelf layoutIfNeeded];
	} completion:^(BOOL finished) {
		if (weakSelf.superview) {
			[weakSelf removeFromSuperview];
			weakSelf.selfConstraints = nil;
		}
	}];
	
	
}

//********** Action *********//

- (void)cancelBtnTi:(UIButton *)button {
	
	if (self.cancelBlock) { self.cancelBlock(); }
	[self dismiss];
	
}

- (void)buttonTi:(UIButton *)button {
	
	int index = (int)button.tag;
	
	if (self.clickBlock) { self.clickBlock(index); }
	
	if ([self.delegate respondsToSelector:@selector(qkActionSheet:clickedAtIndex:)]) {
		[self.delegate qkActionSheet:self clickedAtIndex:index];
	}
	
	[self dismiss];
}

- (void)bgTapGrAction:(UIGestureRecognizer *)gr {
	[self dismiss];
}

#pragma mark - Pri Property

- (UIView *)bgView {
	if (!_bgView) {
		_bgView = [[UIView alloc] init];
		_bgView.alpha = 0;
		_bgView.backgroundColor = COLOR_WITH_HEX_A(0x000000, 0.33);
		
		UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgTapGrAction:)];
		[_bgView addGestureRecognizer:tapGr];
	}
	return _bgView;
}

- (UIView *)buttonsView {
	if (!_buttonsView) {
		_buttonsView = [[UIView alloc] init];
		_buttonsView.backgroundColor = COLOR_WITH_HEX(0xe6e8ef);
	}
	return _buttonsView;
}

- (UIButton *)cancelBtn {
	if (!_cancelBtn) {
		_cancelBtn = [self createButton];
		_cancelBtn.tag = -1;
		[_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
		[_cancelBtn addTarget:self
					   action:@selector(cancelBtnTi:)
			 forControlEvents:UIControlEventTouchUpInside];
		[_cancelBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, TabBarSafeInsetHeight, 0)];
	}
	return _cancelBtn;
}

- (NSMutableArray *)buttons {
	if (!_buttons) {
		_buttons = [NSMutableArray array];
	}
	return _buttons;
}

- (NSMutableArray *)buttonSepViews {
	if (!_buttonSepViews) {
		_buttonSepViews = [NSMutableArray array];
	}
	return _buttonSepViews;
}

@end
